package com.yao.longhan.ui.fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.yao.longhan.ui.base.BaseActivity;
import com.yao.longhan.ui.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by heyao on 2017/7/24.
 */

public class FragmentController {

    private static FragmentController mController;
    private FragmentManager mManager;
    private int containerId;
    private List<BaseFragment> lists;

    public static FragmentController instance(BaseActivity activity, int containerId) {
        if (mController == null) {
            mController = new FragmentController(activity, containerId);
        }
        return mController;
    }

    private FragmentController(BaseActivity activity, int containerId) {
        mManager = activity.getSupportFragmentManager();
        this.containerId = containerId;
        initFragment();
    }

    private void initFragment() {
        lists = new ArrayList<>();
        lists.add(new HomeFragment1());
        lists.add(new BookcaseFragment());
        lists.add(new MyselfFragment());

        FragmentTransaction transaction = mManager.beginTransaction();
        for (BaseFragment baseFragment : lists) {
            transaction.add(containerId, baseFragment, baseFragment.getClass().getSimpleName());
        }
        transaction.commitAllowingStateLoss();
    }

    public void showFragment(int position) {
        hideFragment();
        FragmentTransaction transaction = mManager.beginTransaction();
        BaseFragment baseFragment = lists.get(position);
        transaction.show(baseFragment);
        transaction.commitAllowingStateLoss();
    }

    private void hideFragment() {
        FragmentTransaction transaction = mManager.beginTransaction();
        for (BaseFragment baseFragment : lists) {
            if (baseFragment != null)
                transaction.hide(baseFragment);
        }
        transaction.commitAllowingStateLoss();
    }

    public static void onDestroy() {
        mController = null;
    }

}
